# -*- coding: utf-8 -*-
from typing import List
from fastapi import Depends
from sqlalchemy.orm import Session
from .model import CustomerInformation
from .service import get_customer, get_customers, create_customer, rate_customer
from config.database import get_db
from common.auth import validate_authorization
from common.response import BaseResponse
from pydantic import BaseModel
from customer_information import customer_router
from config.logger import logging

# 获取日志记录器
logger = logging.getLogger(__name__)

# 定义Pydantic模型
class CustomerInformationResponse(BaseModel):
    id: int
    name: str
    phone_number: str
    city: str
    rating: float

    class Config:
        from_attributes = True  # 将 orm_mode 替换为 from_attributes

class CustomerInformationCreate(BaseModel):
    name: str
    phone_number: str
    city: str
    rating: float = 0.0

    class Config:
        from_attributes = True

class RateCustomerRequest(BaseModel):
    customer_id: int
    rating: float

# 定义通用的依赖函数来验证Authorization请求头
@customer_router.get("/list", response_model=BaseResponse[List[CustomerInformationResponse]])
def read_customers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), auth: str = Depends(validate_authorization)):
    """
    获取客户列表，支持分页功能。
    :param skip: 跳过的记录数，用于分页。
    :param limit: 每页的记录数，用于分页。
    :param db: 数据库会话。
    :param auth: 认证信息。
    :return: 包含客户列表的响应。
    """
    try:
        customers = get_customers(db, skip=skip, limit=limit)
        return BaseResponse(code=200, data=customers, message="Success")
    except Exception as e:
        logger.error(f"Error occurred: {e}")
        return BaseResponse(code=500, data=None, message="Internal Server Error")

@customer_router.get("/detail", response_model=BaseResponse[CustomerInformationResponse])
def read_customer(customer_id: int, db: Session = Depends(get_db), auth: str = Depends(validate_authorization)):
    try:
        db_customer = get_customer(db, customer_id=customer_id)
        if db_customer is None:
            return BaseResponse(code=500, data=None, message="Customer not found")
        return BaseResponse(code=200, data=db_customer, message="Success")
    except Exception as e:
        logger.error(f"Error occurred: {e}")  # 打印异常信息到控制台
        return BaseResponse(code=500, data=None, message="Internal Server Error")

@customer_router.post("/add", response_model=BaseResponse[CustomerInformationResponse])
def add_customer(customer: CustomerInformationCreate, db: Session = Depends(get_db), auth: str = Depends(validate_authorization)):
    try:
        if not customer.name or not customer.phone_number:
            return BaseResponse(code=500, data=None, message="Name, phone number are required")
        db_customer = CustomerInformation(**customer.dict())
        created_customer = create_customer(db, customer=db_customer)
        return BaseResponse(code=200, data=created_customer, message="Customer created successfully")
    except Exception as e:
        logger.error(f"Error occurred: {e}")
        return BaseResponse(code=500, data=None, message="Internal Server Error")


# 评分
@customer_router.post("/rate", response_model=BaseResponse[CustomerInformationResponse])
def customer_rate(request: RateCustomerRequest,  db: Session = Depends(get_db), auth: str = Depends(validate_authorization)):
    try:
        db_customer = rate_customer(db, customer_id=request.customer_id, rating=request.rating)
        return BaseResponse(code=200, data=db_customer, message="Customer rated successfully")
    except Exception as e:
        logger.error(f"Error occurred: {e}")
        return BaseResponse(code=500, data=None, message="Internal Server Error")
